package com.ywz.project.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ywz.common.EasyExcelUtils;
import com.ywz.common.ResultResp;
import com.ywz.common.StringUtils;
import com.ywz.common.TreeListUtils;
import com.ywz.project.base.data.entity.TDataStandardIndustry;
import com.ywz.project.base.data.service.ITDataStandardIndustryService;
import com.ywz.project.data.dto.req.StandardIndustryEditReq;
import com.ywz.project.data.dto.req.StandardIndustryTreePageReq;
import com.ywz.project.data.service.StandardIndustryApiService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class StandardIndustryApiServiceImpl implements StandardIndustryApiService {

    @Resource
    private ITDataStandardIndustryService TDataStandardIndustryService;
    private final String INDUSTRY_TREE_KEY = "SAAS_STANDARD_INDUSTRY_TREE_KEY";
    @Resource
    private RedisTemplate<String, List<TDataStandardIndustry>> redisTemplate;

    @Override
    public ResultResp getStandardIndustryTree() {
        if (Boolean.TRUE.equals(redisTemplate.hasKey(INDUSTRY_TREE_KEY))) {
            return ResultResp.success(redisTemplate.opsForValue().get(INDUSTRY_TREE_KEY));
        }
        LambdaQueryWrapper<TDataStandardIndustry> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TDataStandardIndustry::getStatus, 1);
        List<TDataStandardIndustry> list = TDataStandardIndustryService.list(queryWrapper);
        List<TDataStandardIndustry> tIndustries = TreeListUtils.listToTree(list, TDataStandardIndustry.class, "code", "parentCode", "0", "children");
        redisTemplate.opsForValue().set(INDUSTRY_TREE_KEY, tIndustries, 4, TimeUnit.HOURS);
        return ResultResp.success(tIndustries);
    }

    @Override
    public ResultResp getStandardIndustryTreePage(StandardIndustryTreePageReq req) {
        List<TDataStandardIndustry> tIndustries;
        // 从redis中获取行业树，如果不存在则从数据库中获取
        if (Boolean.TRUE.equals(redisTemplate.hasKey(INDUSTRY_TREE_KEY))) {
            tIndustries = redisTemplate.opsForValue().get(INDUSTRY_TREE_KEY);
        } else {
            LambdaQueryWrapper<TDataStandardIndustry> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TDataStandardIndustry::getStatus, 1);
            List<TDataStandardIndustry> list = TDataStandardIndustryService.list(queryWrapper);
            tIndustries = TreeListUtils.listToTree(list, TDataStandardIndustry.class, "code", "parentCode", "0", "children");
            redisTemplate.opsForValue().set(INDUSTRY_TREE_KEY, tIndustries, 4, TimeUnit.HOURS);
        }
        if (TreeListUtils.isEmpty(tIndustries)) return ResultResp.error("数据为空");
        // 进行过滤
        Page<TDataStandardIndustry> page = new Page<>(req.getPageNum(), req.getPageSize());
        if (!StringUtils.isEmpty(req.getName())) {
            TDataStandardIndustry filterIndustry = TreeListUtils.filterTreeByExistsFieldValue(tIndustries, TDataStandardIndustry.class, "name", req.getName(), "children");
            tIndustries.clear();
            tIndustries.add(filterIndustry);
        }
        // 分页
        page.setTotal(tIndustries.size());
        page.setRecords(tIndustries.subList((req.getPageNum() - 1) * req.getPageSize(), Math.min(req.getPageNum() * req.getPageSize(), tIndustries.size())));
        return ResultResp.success(page);
    }

    @Override
    public ResultResp deleteStandardIndustry(Integer id) {
        if (StringUtils.isNull(id))
            return ResultResp.error("参数为空");
        boolean removed = TDataStandardIndustryService.removeById(id);
        if (removed)
            redisTemplate.delete(INDUSTRY_TREE_KEY);
        return removed ? ResultResp.success() : ResultResp.error();
    }

    @Override
    public ResultResp editStandardIndustry(StandardIndustryEditReq req) {
        // 数据校验
        if (StringUtils.isEmpties(req.getCode(), req.getName(), req.getParentId()))
            return ResultResp.error("参数不能为空");
        if (StringUtils.isOverLength(255, req.getCode(), req.getName(), req.getParentId()))
            return ResultResp.error("参数长度过长");
        // 编辑数据
        TDataStandardIndustry tIndustry = new TDataStandardIndustry();
        BeanUtils.copyProperties(req, tIndustry);
        boolean saved = TDataStandardIndustryService.saveOrUpdate(tIndustry);
        if (saved)
            redisTemplate.delete(INDUSTRY_TREE_KEY);
        return saved ? ResultResp.success() : ResultResp.error();
    }

    @Override
    public ResultResp exportStandardIndustry(HttpServletResponse response) {
        if (redisTemplate.hasKey(INDUSTRY_TREE_KEY)) {
            List<TDataStandardIndustry> tIndustries = redisTemplate.opsForValue().get(INDUSTRY_TREE_KEY);
            if (TreeListUtils.isEmpty(tIndustries)) return null;
            List<TDataStandardIndustry> children = TreeListUtils.treeToList(tIndustries, TDataStandardIndustry.class, "children");
            EasyExcelUtils.defaultWrite("行业分类", "行业分类", children, TDataStandardIndustry.class, response);
        }
        return null;
    }
}
